package net.oschina.simpleplus.erpc.core;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.GeneratedMessageV3;

import net.oschina.simpleplus.erpc.support.ProtobufCache;

public class ERpcResp {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ERpcResp.class);

	private final String msgId;
	private final Class<?> returnType;
	private Object value;
	
	private CountDownLatch countWait = new CountDownLatch(1);
	
	public ERpcResp(String msgId, Class<?> returnType) {
		super();
		this.msgId = msgId;
		this.returnType = returnType;
	}
	public String getMsgId() {
		return msgId;
	}
	public Object getValue()throws Exception {
		if(!countWait.await(10, TimeUnit.SECONDS)){
			throw new RuntimeException("请求超时！");
		}
		return value;
	}
	public void setValue(ERpcResultEntity eRpcResultEntity) {
		if(eRpcResultEntity != null && eRpcResultEntity.getBody() != null){
			try {
				value = ProtobufCache.merge(returnType, eRpcResultEntity.getBody());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			LOGGER.error("invoke error:[code:{}, msg:{}]", eRpcResultEntity.getCode(), eRpcResultEntity.getMsg());
		}
		countWait.countDown();
	}
	public Class getReturnType() {
		return returnType;
	}
	
}
